<?php

namespace yak\layui\models\admin;

use yii\base\Model;

/**
 * Class RegForm
 * @package yak\layui\models\admin
 */
class RegForm extends Model
{
    public $name;
    public $username;
    public $email;
    public $password;
    public $confirmPassword;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'email', 'name'], 'trim'],
            [['username', 'email', 'password', 'confirmPassword'], 'required'],
            [['username', 'email', 'name'], 'string', 'min' => 2, 'max' => 255],
            [['password', 'confirmPassword'], 'string', 'min' => 6],
            ['email', 'email'],
            ['confirmPassword', 'compare', 'compareAttribute' => 'password', 'message' => '两次密码不一致'],

            ['username', 'unique', 'targetClass' => User::class, 'message' => '用户已存在'],
            ['email', 'unique', 'targetClass' => User::class, 'message' => '邮箱已注册'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'name' => '姓名',
            'username' => '用户名',
            'email' => '邮箱',
            'password' => '密码',
            'confirmPassword' => '确认密码'
        ];
    }

    /**
     * @return User|null
     * @throws \yii\base\Exception
     */
    public function register()
    {
        if (!$this->validate()) {
            return null;
        }
        $user = new User();
        $user->name = $this->name;
        $user->username = $this->username;
        $user->email = $this->email;
        $user->setPassword($this->password);
        $user->generateAuthKey();

        return $user->save() ? $user : null;
    }
}
